import { defineStore } from 'pinia';
import { propertyApi } from '@/api/properties'; // 确保路径正确
import { useAuthStore } from '@/stores/auth';

export const usePropertyStore = defineStore('property', {
  state: () => ({
    propertyList: [],
    currentPage: 1,
    totalItems: 0,
    pageSize: 20,
    loading: false,
    error: null,
    currentQueryParams: {}, // 用于存储当前搜索的参数，以便加载更多时使用
    hasMore: true, // 表示是否还有更多数据可以加载
     /**
     * @type {Array<object>}
     * 存储当前选中房源的公开评论列表
     */
    currentPropertyReviews: [],
    /**
     * @type {boolean}
     * 评论区的加载状态
     */
    reviewsLoading: false,
  }),

  actions: {
    async fetchProperties(params = {}, useApiKey = false, loadMore = false) {
      this.loading = true;
      const authStore = useAuthStore();

      let requestPage;
      if (loadMore) {
        requestPage = this.currentPage + 1;
      } else {
        requestPage = params.page || 1;
        const { page, pageSize, ...restParams } = params;
        this.currentQueryParams = restParams;
      }

      const requestParams = {
        ...this.currentQueryParams,
        page: requestPage,
        pageSize: params.pageSize || this.pageSize,
        name: params.name !== undefined ? params.name : this.currentQueryParams.name,
        district: params.district !== undefined ? params.district : this.currentQueryParams.district, // 修正字段
        sub_district: params.sub_district !== undefined ? params.sub_district : this.currentQueryParams.sub_district, // 修正字段
        sw_lat: params.sw_lat !== undefined ? params.sw_lat : this.currentQueryParams.sw_lat,
        sw_lng: params.sw_lng !== undefined ? params.sw_lng : this.currentQueryParams.sw_lng,
        ne_lat: params.ne_lat !== undefined ? params.ne_lat : this.currentQueryParams.ne_lat,
        ne_lng: params.ne_lng !== undefined ? params.ne_lng : this.currentQueryParams.ne_lng,
        center_lat: params.center_lat !== undefined ? params.center_lat : this.currentQueryParams.center_lat,
        center_lng: params.center_lng !== undefined ? params.center_lng : this.currentQueryParams.center_lng,
        radius: params.radius !== undefined ? params.radius : this.currentQueryParams.radius,
      };

      // 清理 undefined 的参数，因为后端可能不希望接收到值为 undefined 的键
      Object.keys(requestParams).forEach(key => {
        if (requestParams[key] === undefined || requestParams[key] === '') {
          delete requestParams[key];
        }
      });

      // 如果需要使用 API Key，则将其添加到请求参数中
      // poiApi.getPOIs 会处理将其放入 header
      if (useApiKey && authStore.isAuthenticated && authStore.getApiKey) {
        requestParams.apikey = authStore.getApiKey;
      } else {
        // 确保如果之前有 apikey，现在没有了就移除它
        delete requestParams.apikey;
      }

      try {
         console.log('Requesting properties with params:', requestParams); // 添加日志
        // 统一调用 poiApi.getPOIs
        const response = await propertyApi.getProperties(requestParams);

        const resData = response.data?.data; // 假设你的API响应结构是 { data: { list: [], pagination: {} } }
                                          // 或者直接是 { list: [], pagination: {} }，根据你的API调整
        console.log('API Response:', {
          page: requestPage,
          listLength: resData?.list?.length,
          pagination: resData?.pagination,
          list: resData?.list // 输出列表内容以便排查
        });
        if (resData && resData.list && resData.pagination) {
          if (loadMore) {
              const newList = resData.list.filter(
              newItem => !this.propertyList.some(existingItem => existingItem.id === newItem.id)
            );
            this.propertyList = [...this.propertyList, ...resData.list];
          } else {
            this.propertyList = resData.list;
          }
          this.totalItems = resData.pagination.total_items || resData.pagination.total || 0;
          this.currentPage = requestPage; // 强制使用 requestPage 更新
          this.pageSize = resData.pagination.per_page || resData.pagination.pageSize || this.pageSize;
          this.hasMore = this.propertyList.length < this.totalItems;
          this.error = null;
          console.log('Properties fetched:', resData.list.length, 'Current Total in list:', this.propertyList.length, 'Properties Total:', this.totalItems);
        } else {
          console.error("Unexpected data structure received for POIs or no data:", resData);
          if (!loadMore) {
            this.propertyList = [];
            this.totalItems = 0;
          }
          this.hasMore = false;
          this.error= '数据格式错误'// 如果数据结构不符或没有数据，则认为没有更多
        }
      } catch (error) {
        this.error = error.response?.data?.message || error.message || '获取 Property 数据失败';
        console.error('Error fetching Properties:', error);
      } finally {
        this.loading = false;
      }
    },

      /**
     * 获取指定房源的评论列表
     * @param {number} propertyId
     */
    async fetchReviewsForProperty(propertyId) {
      this.reviewsLoading = true;
      this.currentPropertyReviews = []; // 先清空
      try {
        const response = await propertyApi.getPropertyReviews(propertyId);
        // 假设后端返回的数据在 response.data.data 中
        this.currentPropertyReviews = response.data?.data || [];
      } catch (error) {
        console.error('获取评论失败:', error);
        this.currentPropertyReviews = []; // 出错时清空
        ElMessage.error(error.response?.data?.message || '加载评论失败');
      } finally {
        this.reviewsLoading = false;
      }
    },

    resetPropertyState() {
        this.propertyList = [];
        this.currentPage = 1;
        this.totalItems = 0;
        this.currentQueryParams = {};
        this.hasMore = true; // 重置时假设有数据，除非首次加载后发现没有
    },

    // Admin 操作保持不变
    async createProperty(data) {
      console.log(data);
      const authStore = useAuthStore();
      const requestData = {...data};
      if (authStore.isAuthenticated && authStore.getApiKey) {
        // 如果 createPOI 也需要 API Key (取决于你的后端设计)
        // 通常创建操作是通过认证的，可能不需要显式传递 Key，而是通过 JWT/Session
        // 但如果你的 createPOI 也像 getPOIs 一样通过 X-API-KEY，则需要添加
        // requestData.apikey = authStore.getApiKey; // (如果需要)
      }
      await propertyApi.createProperty(requestData);
      // 创建后刷新，应为全新搜索，并考虑当前是否使用了 API Key
      await this.fetchProperties({}, authStore.isAuthenticated && !!authStore.getApiKey, false);
    },

    async updateProperty(data) {
      const authStore = useAuthStore();
      const requestData = { ...data };
      if (authStore.isAuthenticated && authStore.getApiKey) {
        requestData.apikey = authStore.getApiKey;
      }
      console.log(requestData);
      await propertyApi.updateProperty(requestData.id, requestData);
      await this.fetchProperties(
        { page: this.currentPage, pageSize: this.pageSize, ...this.currentQueryParams },
        authStore.isAuthenticated && !!authStore.getApiKey,
        false
      );
    },

    async deleteProperty(id) {
      const authStore = useAuthStore();
      // 删除操作通常也需要认证，但 API Key 的传递方式同上
      await propertyApi.deleteProperty(id); // 假设 deletePOI 不需要显式传递 apikey
      // 删除后刷新，考虑当前页和 API Key 使用状态
      await this.fetchProperties({ page: this.currentPage, pageSize: this.pageSize, ...this.currentQueryParams }, authStore.isAuthenticated && !!authStore.getApiKey, false);
    },
  },
});
